var isBuying = false;

function Main() {

}

$.extend(Main.prototype, {
    init: function (key) {
        var self = this;
        this.nestJSSDK = sessionStorage.getItem("JS_SDK");
        this.bindEvents();
        if (key == 'productiondetail' || key == 'status' || key == 'orderlist') {

            this.nestJSSDK = new NestCloudSeckill();
            this.nestJSSDK.init('http://47.94.129.86:8000', 'http://47.94.129.86:8000', 'test-hss3', sessionStorage.getItem("userId"), sessionStorage.getItem("token"));
            if (key == 'productiondetail') {
                this.nestJSSDK.updateTimeCallback = function (_nestJSSDK) {
                    $('.buyNow').prop('disabled', true).css('background', 'gray');


                    if (_nestJSSDK.seckStatus() == 0) {
                        $('.startTime_span').html('数据正在加载中');
                    }
                    else if (_nestJSSDK.seckStatus() == 1) {
                        var result = _nestJSSDK.seckStatusDate(_nestJSSDK.currentMicSecond, _nestJSSDK.serverStartMicSecond);
                        if (result.days > 0) {
                            result = "距开始：" + result.days + ":" + result.hours + ":" + result.minutes + ":" + result.seconds;
                        }
                        else {
                            result = "距开始：" + result.hours + ":" + result.minutes + ":" + result.seconds;
                        }
                        $('.startTime_span').html(result);
                    }
                    else if (_nestJSSDK.seckStatus() == 2) {
                        var result = _nestJSSDK.seckStatusDate(_nestJSSDK.currentMicSecond, _nestJSSDK.serverEndMicSecond);
                        if (result.days > 0) {
                            result = "距结束：" + result.days + ":" + result.hours + ":" + result.minutes + ":" + result.seconds;
                        }
                        else {
                            result = "距结束：" + result.hours + ":" + result.minutes + ":" + result.seconds;
                        }
                        $('.startTime_span').html(result);
                        $('.buyNow').prop('disabled', false).css('background', '#ea3939');
                    }
                    else if (self.nestJSSDK.seckStatus() == 3) {
                        $('.startTime_span').html('活动已结束');
                    }
                };

                this.nestJSSDK.productinfo(function (payload) {
                    $('.ptxt').html("¥&nbsp;" + "0");
                    if (payload.productInfo.stockCount > 0)
                        self.nestJSSDK.updateTimeCallback(self.nestJSSDK);
                    else {
                        self.nestJSSDK.updateTimeCallback = null;
                        $('.buyNow').prop('disabled', true).css('background', 'gray');
                        $('.startTime_span').html('活动已结束');
                    }
                }, function (error) {
                    $('.startTime_span').html('活动已结束');
                });
            }
            else if (key == 'status') {

                self.showLoading();

                this.nestJSSDK.productinfo(function (payload) {
                    self.statusChecking();

                }, function (error) {
                    self.hideLoading();
                    alert('加载数据出现错误');
                });


            }
            else if (key == 'orderlist') {
                self.showLoading();
                self.nestJSSDK.myOrders(function (request_id, payload) {
                    self.hideLoading();
                    var str = '';
                    for (var i = 0; i < payload.length; i++) {
                        let order = payload[i] ? payload[i] : {},
                            oderId_div = "<div class='order-id'>订单号：" + order.requestId + "</div>",
                            orderName_div = "<div class='order-id'>商品名称：" + (order.productName||"夏日饮料") + "</div>";
                        str += "<div class='order-list'><img class='order-img' src='" + (order.productImg||"1.jpg") + "' /><div class='order-right'>" + orderName_div + oderId_div + "</div></div>";

                    }
                    $('#lsOrder').html(str);

                }, function () {
                    self.hideLoading();
                    alert('订单数据暂未能获取到!');
                    // let payload = [
                    //     {
                    //         "requestId":"3231q2132131d7sadu7gs7d7hsfts",
                    //         "productName":"iPhone8",
                    //         "productImg":"http://activityqn.infinitus.com.cn/nest/2017/08/01/t0gkmlpwoyaaxs7.png"
                    //     },
                    //     {
                    //         "requestId":"3231q2132131d7sadu7gs7d7hsfts",
                    //         "productName":"iPhone8",
                    //         "productImg":"1.jpg"
                    //     },{
                    //         "requestId":"3231q2132131d7sadu7gs7d7hsfts",
                    //         "productName":"iPhone8",
                    //         "productImg":"http://activityqn.infinitus.com.cn/nest/2017/08/01/t0gkmlpwoyaaxs7.png"
                    //     }
                    // ];
                });

            }

        }
    },
    statusChecking: function () {
        var self = this;
        var requestId = sessionStorage["requestId"];
        //查询是否秒杀成功
        self.nestJSSDK.apiStatus(requestId, function (data) {
            if (data.requestId == requestId) {
                if (data.isSuccess == 'success') {
                    self.hideLoading();
                    $(".mainBox").show();
                    $(".YBox").show();
                    $(".NBox").hide();
                }
                else if ( data.isSuccess == 'fail' && data.message == '重复秒杀' ) {
                    self.hideLoading();
                    $(".mainBox").show();
                    $(".NBox").hide();
                    $(".YBox").hide();
                    $(".RBox").show();
                }
                else if (data.isSuccess == 'fail') {
                    self.hideLoading();
                    $(".mainBox").show();
                    $(".NBox").show();
                    $(".YBox").hide();
                }
            }
            else {
                setTimeout(function () {
                    self.statusChecking();
                }, 3000);
            }
        }, function () {
            setTimeout(function () {
                self.statusChecking();
            }, 3000);

        });
    },

    showLoading: function () {
        var loadHtml = '<div class="spinner_maskBox"><div class="spinner"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div>'
        $("body").append(loadHtml);
        $(".spinner").show();
    },
    hideLoading: function () {
        $(".spinner_maskBox").remove();
    },
    bindEvents: function () {
        var self = this
        $(document).on('click', '.loginBtn', function () {
            var username = $('#userName').val().trim();
            if (username.length < 1) {
                alert("请输入员工工号");
                return;
            }
            self.showLoading();
            $.ajax({
                url: "http://killseck.shifu51.cn:8000/seckill-login",
                type: "POST",
                dataType: 'json',
                data: {
                    "username": username,
                    "password": "123456"
                },
                success: function (data) {
                    self.hideLoading();
                    sessionStorage.setItem("userId", username);
                    sessionStorage.setItem("token", data.token);
                    location.href = "prodetail.html";
                },
                error: function (data) {
                    self.hideLoading();
                    alert("接口调用失败");
                }
            });


        });
        $(document).on('click', '.buyBtn', function () {
            location.href = "prodetail.html";
        });

        $(document).on('click', '.buyNow', function () {
            if (isBuying) return;
            isBuying = true;
            $('.buyNow').prop('disabled', true).css('background', 'gray');
            self.showLoading();
            //秒杀开始，抢
            self.nestJSSDK.seckill(function (seckillStatus, requestId) {
                isBuying = false;
                if (seckillStatus == 'queuing') {
                    self.hideLoading();
                    $('.buyNow').prop('disabled', true).css('background', 'gray');
                    console.log(requestId);
                    sessionStorage.setItem("requestId", requestId);
                    location.href = "status.html";

                }
                else if (seckillStatus == 'not started') {
                    self.hideLoading();
                    $('.buyNow').prop('disabled', false).css('background', '#ea3939');
                    alert('请别乱来，秒杀还未开始。');
                }
                else {
                    self.hideLoading();
                    self.nestJSSDK.updateTimeCallback = null;
                    $('.startTime_span').html('活动已结束');
                    $('.buyNow').prop('disabled', true).css('background', 'gray');
                    alert('你来迟一步了，秒杀已经抢完，谢谢参与。');
                }

            }, function (data) {
                isBuying = false;
                self.hideLoading();
                self.nestJSSDK.updateTimeCallback = null;
                $('.startTime_span').html('活动已结束');
                $('.buyNow').prop('disabled', true).css('background', 'gray');
                alert('你来迟一步了，秒杀已经抢完，谢谢参与。');

            });

        });


    }

});


var main = new Main();
